/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session;

import entities.Artiste;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Nordinator
 */
@Stateless
@LocalBean
public class ArtisteManager {
    @PersistenceContext(unitName = "Project-MP3-Rumble-ejbPU")
    private EntityManager em;

    public void persist(Object object) {
        em.persist(object);
    }

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")

    public List<Artiste> getAllArtistes() {
        Query query = em.createNamedQuery("Artiste.findAll");
        return query.getResultList();
    }   

    public Artiste update(Artiste artiste) {
        return em.merge(artiste);
    }
    
    public Artiste ajouterArtiste(String artiste, String albumName){
        try{
            Query query = em.createNamedQuery("Artiste.findByName");
            query.setParameter("name", artiste);
            if(query.getResultList().isEmpty()){
                Artiste art = new Artiste(artiste);
                art.addAlbum(albumName);
                em.persist(art);
                return null;
            }else{
                Artiste art = (Artiste) query.getResultList().get(0);
                art.addAlbum(albumName);
                return em.merge(art);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
    
    public void Test(){
        this.ajouterArtiste("Queen","A Night at the Opera");
        this.ajouterArtiste("Coldplay","Vive la vida ans all his friend");
        this.ajouterArtiste("ACDC", "highway to hell");
        this.ajouterArtiste("Metallica", "Black album");
    }
}
